package com.cc.flyingfish.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cc.flyingfish.entity.OrderInfoEntity;
import com.cc.flyingfish.mapper.OrderInfoMapper;
import com.cc.flyingfish.points.PointsClient;
import com.cc.flyingfish.service.OrderInfoService;
import com.cc.flyingfish.util.BusinessStatusConstant;
import com.cc.flyingfish.vo.CommonResponse;
import com.cc.flyingfish.vouchers.VouchersClient;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author CHENCHEN
 * @since 2023-03-08
 */
@Slf4j
@Transactional(rollbackFor = Exception.class)
@Service
public class OrderInfoServiceImp extends ServiceImpl<OrderInfoMapper, OrderInfoEntity> implements OrderInfoService {

    @Autowired
    private VouchersClient vouchersClient;

    @Autowired
    private PointsClient pointsClient;

    @GlobalTransactional(rollbackFor = Exception.class)
    @Override
    public CommonResponse insertOrderInfo(){
        OrderInfoEntity orderInfoEntity = new OrderInfoEntity()
                .setOrderNo(UUID.randomUUID().toString().replaceAll("-", "").substring(0, 16))
                .setStatus("1")
                .setUserId(999l);
        this.save(orderInfoEntity);
        log.info("Seata全局事务id=================>{}", RootContext.getXID());
        CommonResponse index = vouchersClient.index();
        if(index.getCode().equals(BusinessStatusConstant.BUSINESSEXCEPTION)){
            throw new RuntimeException("HTTP Openfeign to vouchersClient.index() error =====================>{}");
        }
        log.info("vouchersClient.index()=================>{}", index);
        CommonResponse response = pointsClient.index();
        if(response.getCode().equals(BusinessStatusConstant.BUSINESSEXCEPTION)){
            throw new RuntimeException("HTTP Openfeign to pointsClient.index() error");
        }
        log.info("pointsClient.index()=================>{}", response);

        return CommonResponse.SUCCESS;
    }
}
